package ui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import document.Record;

/*
 * 磁盘界面
 * 时间：2014-10-29
 * @version:1.0
 */
public class DiskUi {

	private Frame frame;
	private javax.swing.JTree jTree;
	private javax.swing.JScrollPane s, aboutScroll;
	private javax.swing.JTextField text;
	private javax.swing.JTextArea aboutText;
	private javax.swing.JButton button;
	private javax.swing.JPopupMenu menu;
	private javax.swing.JMenuItem menu1;
	private javax.swing.JMenuItem menu2, menu3, menu4;
	private DefaultMutableTreeNode root;
	private document.Disk disk;
	private document.ManagingDirectory managingDirectory;
	private document.ManagingCommonFile managingCommonFile;
	private DefaultMutableTreeNode selectNode = null;
	private String path;

	private class Frame extends javax.swing.JFrame {

		// 绘制磁盘状态
		public void paint(java.awt.Graphics g) {
			super.paint(g);

			int[] fat = disk.inputDiskToFat();

			int x = 320;
			int y = 35;
			int index = 0;
			fat[0] = 255;
			for (int i = 0; i < 16; i++) {
				for (int j = 0; j < 8; j++) {
					if (fat[index] != 0) {
						g.setColor(Color.green);
					} else {
						g.setColor(Color.BLACK);
					}
					// System.out.println(fat[index]);
					g.fillRect(x + (j * 21), y + (i * 21), 10, 10);
					index++;
				}
			}

		}

	}

	public void start(){
		frame.setVisible(true);
	}
	
	public DiskUi() {
		managingDirectory = new document.ManagingDirectory();
		managingCommonFile = new document.ManagingCommonFile();
		disk = new document.Disk();
		frame = new Frame();
		path = "Root";
		init();
		addListener();
	}

	// 初始化调用
	private void init() {

		T t = new T();
		t.setDaemon(true);
		t.start();

		frame.setSize(510, 400);
		frame.setResizable(false);
		frame.setTitle("磁盘管理");
		frame.setLayout(null);
		frame.setLocationRelativeTo(null);
		addTree();

		menu = new javax.swing.JPopupMenu();
		menu1 = new javax.swing.JMenuItem("删除");
		menu2 = new javax.swing.JMenuItem("创建文件");
		menu3 = new javax.swing.JMenuItem("创建文件夹");
		menu4 = new javax.swing.JMenuItem("查看");
		menu.add(menu1);
		menu.add(menu2);
		menu.add(menu3);
		menu.add(menu4);
		frame.add(menu);

		text = new javax.swing.JTextField();
		text.setBounds(10, 220, 200, 30);
		frame.add(text);

		button = new javax.swing.JButton();
		button.setBounds(220, 220, 80, 30);
		button.setText("执行");
		frame.add(button);

		StringBuilder bu = new StringBuilder();
		bu.append("命令说明:\n");
		bu.append("创建文件:create 文件路径和名字 文件大小\n");
		bu.append("删除文件:delete 文件路径和名字\n");
		bu.append("创建文件夹:mkdir 文件夹路径和名字\n");
		bu.append("删除非空文件夹:rmdir 文件夹路径和名字\n");
		bu.append("删除文件夹:deldir 文件夹路径和名字\n");
		bu.append("显示文件:type 文件路径和名字\n");
		bu.append("拷贝文件:copy 文件路径和名字 文件路径和名字\n");
		aboutText = new javax.swing.JTextArea(bu.toString());
		aboutText.setEditable(false);
		aboutScroll = new javax.swing.JScrollPane(aboutText);
		aboutScroll.setBounds(10, 260, 300, 100);
		frame.add(aboutScroll);

		frame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
		readDisk();
		//frame.setVisible(true);

	}

	// 添加tree控件
	private void addTree() {
		buildTree();
		s = new javax.swing.JScrollPane(jTree);
		s.setBounds(10, 10, 300, 200);
		frame.add(s);
	}

	// 生成树
	private void buildTree() {
		root = new DefaultMutableTreeNode("Root");
		jTree = new javax.swing.JTree(root, true);
	}

	/*
	 * 遍历目录下的文件和文件夹
	 * 
	 * @param pNode jTree父节点
	 * 
	 * @param nowRecord 文件记录
	 * 
	 * @param road 父目录
	 * 
	 * @return
	 */
	private void listFile(DefaultMutableTreeNode pNode, Record nowRecord,
			String road) {
		Record[] records = managingDirectory.seeADirContent(road
				+ nowRecord.getName());
		for (Record record : records) {
			if (record == null) {
				continue;
			}
			if (record.getName().equals(" ")) {
				continue;
			}
			if (record.getAttribute() == ' ') {
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(
						record.getName());
				pNode.add(node);
				listFile(node, record, road + "/" + record.getName());
			} else {
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(
						record.getName());
				node.setAllowsChildren(false);
				pNode.add(node);
			}

		}
	}

	// 获取树所需信息
	private void readDisk() {

		Record[] records = controller.Disk.getObject().readRecordsFromABlock(2);
		DefaultMutableTreeNode tempNode = root;
		root.removeAllChildren();
		for (Record record : records) {
			if (record.getName().equals(" ")) {
				continue;
			}
			if (record.getAttribute() == ' ') {
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(
						record.getName());
				tempNode.add(node);
				listFile(node, record, "Root/");
			} else {
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(
						record.getName());
				node.setAllowsChildren(false);
				tempNode.add(node);
			}

		}
		jTree.updateUI();
	}

	// 执行命令行
	private void execute(String order) throws Exception {

		String[] strs = order.split(" ");
		int size = (int) (Math.random() * 30);

		if (order.startsWith("create ")) {
			managingCommonFile.createACommonFile(strs[1],
					Integer.parseInt(strs[2]));
		} else if (order.startsWith("delete ")) {
			managingCommonFile.deleteAFile(strs[1]);
		} else if (order.startsWith("mkdir ")) {
			managingDirectory.createADirectory(strs[1], 1);
		} else if (order.startsWith("deldir ")) {
			if (tryDeleteAllFile(strs[1], true)) {
				JOptionPane.showMessageDialog(null, "删除文件夹成功");
			} else {
				JOptionPane.showMessageDialog(null, "删除文件夹失败");
			}
		} else if (order.startsWith("rmdir ")) {
			if (tryDeleteAllFile(strs[1], false)) {
				JOptionPane.showMessageDialog(null, "删除文件夹成功");
			} else {
				JOptionPane.showMessageDialog(null, "删除文件夹失败");
			}
		} else if (order.startsWith("copy ")) {
			if (copy(strs[1], strs[2])) {
				JOptionPane.showMessageDialog(null, "复制文件成功");
			} else {
				JOptionPane.showMessageDialog(null, "复制文件失败");
			}
		} else if (order.startsWith("type ")) {
			type(strs[1]);
		} else {
			throw new Exception();
		}
		text.setText("");
		// JOptionPane.showMessageDialog(null, "命令已经执行！");
	}

	// 添加事件监听
	private void addListener() {

		button.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {

				String str = text.getText();

				if (!str.equals("")) {
					try {
						execute(str);
					} catch (Exception error) {
						JOptionPane.showMessageDialog(null, "命令有误！");
					}
				} else {
					JOptionPane.showMessageDialog(null, "命令不能为空！");
				}
				updateUi();
			}

		});

		jTree.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {

				if (e.getButton() == 3) {
					menu.show(frame.getContentPane(), e.getPoint().x + 20,
							e.getPoint().y + 15);
				} else {
					try {

						TreePath p = jTree.getPathForLocation(e.getX(),
								e.getY());
						selectNode = (DefaultMutableTreeNode) p
								.getLastPathComponent();
						path = jTree.getSelectionPath().toString();
						path = path.substring(1, path.length() - 1);
						path = path.replace(",", "/");
						path = path.replace(" ", "");
					} catch (Exception error) {
					}
				}
			}

		});

		menu1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub

				if (!selectNode.getAllowsChildren()) {
					deleteFileOrDir(true);
				} else {
					deleteFileOrDir(false);
				}
			}

		});

		menu2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				createFileOrDir(true);
			}

		});

		menu3.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				createFileOrDir(false);
			}

		});

		menu4.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				type(path);
			}

		});

	}

	/*
	 * 删除文件或文件夹
	 * 
	 * @param type 如果为true，删除文件，否则删除文件夹
	 */
	private boolean deleteFileOrDir(boolean type) {
		boolean sign = true;
		if (type) {
			managingCommonFile.deleteAFile(path);
			// JOptionPane.showMessageDialog(null, "文件");
		} else {
			sign = tryDeleteAllFile(path, true);
			// managingDirectory.deleteADir(path);
			// JOptionPane.showMessageDialog(null, "文件夹");
		}
		updateUi();
		return sign;
	}

	/*
	 * 创建文件或文件夹
	 * 
	 * @param type 如果为true，创建文件，否则创建文件夹
	 */
	private void createFileOrDir(boolean type) {
		String str = JOptionPane.showInputDialog(null);
		int size = (int) (Math.random() * 30);
		if (str != null && !str.equals("")) {
			String tempPath = path + "/" + str;
			if (type) {
				managingCommonFile.createACommonFile(tempPath, size);
			} else {
				managingDirectory.createADirectory(tempPath, 1);
			}

		} else {

		}
		updateUi();
	}

	/*
	 * 尝试删除文件夹
	 * 
	 * @param type 如果为true，则删除非空目录，删除所有文件，如果为false,则不能删除非空目录
	 * 
	 * @return 删除文件夹结果
	 */
	private boolean tryDeleteAllFile(String path, boolean type) {
		Record[] records = managingDirectory.seeADirContent(path);
		if (type) {

			for (Record r : records) {
				if (r != null) {
					if (r.getAttribute() == ' ') {
						// 文件夹
						tryDeleteAllFile(path + "/" + r.getName(), true);
					} else {
						// 文件
						managingCommonFile
								.deleteAFile(path + "/" + r.getName());
					}
				}
			}
			managingDirectory.deleteADir(path);

		} else {
			boolean sign = true;
			for (Record r : records) {
				if (r != null) {
					sign = false;
					break;
				}
			}
			if (sign) {
				managingDirectory.deleteADir(path);
			}
			return sign;
		}
		return true;
	}

	/*
	 * 复制文件
	 * 
	 * @param path1 原路径
	 * 
	 * @param path2 目标路径
	 * 
	 * @return boolean 结果
	 */
	private boolean copy(String path1, String path2) {
		int size = managingCommonFile.seeAFile(path1).getLength();
		managingCommonFile.createACommonFile(path2, size);
		// ManagingCommonFile
		return true;
	}

	/*
	 * 显示文件信息
	 * 
	 * @param path 文件路径
	 */
	private void type(String path) {
		Record r = managingCommonFile.seeAFile(path);
		JOptionPane.showMessageDialog(
				null,
				"文件路径:" + path + "\n文件名：" + r.getName() + "\n文件大小："
						+ r.getLength());
		updateUi();
	}

	// 刷新ui
	private void updateUi() {
		readDisk();
		jTree.updateUI();
		frame.repaint();
	}

	private class T extends Thread {
		public void run() {
			while (true) {
				try {
					try{
					frame.repaint();
					}catch(Exception error){}
					Thread.sleep(1000);
				} catch (Exception error) {

				}
			}
		}
	}

}
